import loadable from '@loadable/component'
import {Skeleton} from 'antd'


//我们要忽略的文件
const FILTER_EXCLUDE = [
    'login',
    'components',
    'utils',
];

export const layoutRouter = (router) => {
    const layoutObject = []
    for (let i = 0; i < router.length; i++) {
        const {path} = router[i]
        if (path !== 'login') {
            layoutObject.push(router[i])
        }
    }
    return layoutObject
}


export const filterConfig = (path) => {
    for (let i = 0; i < FILTER_EXCLUDE.length; i++) {
        let item = FILTER_EXCLUDE[i];

        // 如果不是文件类型则转为文件夹
        if (!item.includes('.')) {
            item = `/${item}/`;
        }

        if (path.includes(item)) return true;
    }

    return false;
}
// 整理获取到配置的key，将他整理为路由用的path
export const getPageRouterPath = (path) => {
    // 获取page数据后面数据
    const pageIndex = path.indexOf('pages') + 5;
    // 文件后缀
    const lastIndex = path.lastIndexOf('.');
    // 去除pages和文件后缀
    let result = path.substring(pageIndex, lastIndex);

    // 如果是首页则直接返回/
    if (result === '/index') return '/';

    // 如果结尾是index则去除
    if (result.includes('index')) {
        const indexIdx = result.lastIndexOf('index') + 5;
        if (indexIdx === result.length) {
            result = result.substring(0, result.length - 6);
        }
    }

    return result;
}

export const createRouter = (pageInfo) => {
    const routers = []
    for (const key in pageInfo) {
        // 是否在排除名单中
        const isExclude = filterConfig(key);
        if (isExclude) continue;
        const path = getPageRouterPath(key);
        if (path === '/login') continue;
        //输出component,当组件加载的时候展示骨架屏等待相应
        const ComponentNode = loadable(pageInfo[key], {
            fallback: <Skeleton active />
        });

        routers.push({
            path,
            element: <ComponentNode/>
        });
    }
    return routers
}
